<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="!form.id ? $t('add') : $t('update')"
    :visible.sync="visible"
    width="85vw"
  >
    <!--    @keyup.enter.native="formSubmitHandle()"-->
    <el-form
      :model="form"
      :rules="dataRule"
      label-width="120px"
      ref="dataForm"
      v-loading="loading"
    >
      <el-form-item
        label="所属设备"
        prop="productInfoId">
        <el-cascader
          clearable
          placeholder="所属设备"
          @change="onProductSelectChange"
          class="product-info-item-select"
          v-model="selectedInfos"
          :options="productInfos"
        />
      </el-form-item>

      <el-form-item
        label="设备ID"
        prop="deviceId">
        <el-input
          placeholder="设备ID"
          v-model="form.deviceId"
          size="normal"
        />
      </el-form-item>
      <el-form-item
        label="集合名称"
        prop="collectionName">
        <!--                        :placeholder="$t('model.name')"
                                            -->
        <el-input
          placeholder="集合名称"
          v-model="form.collectionName"
          size="normal"
        />
      </el-form-item>

      <el-form-item
        label="关联用例"
        prop="testCaseList">
        <!--        <div class="selected-test-cases">-->
        <!--        <el-tag closable v-for="item in form.testCaseList" :key="item.id"  @close="handleTestCaseClose(item)">{{item.taskName}}</el-tag>-->

        <!--        </div>-->

        <div class="test-case-container">
          <div class="test-case-list original-cases">
            <div class="case-list-title">
              现有用例
            </div>
            <ul>
              <!--              @change="handleTestCaseChecked(item)"-->
              <li
                v-for="item in testCases"
                :key="'original-' + item.id">
                <el-checkbox
                  v-model="item.checked"
                >{{ item.taskName }}-ID:{{
                  item.testCaseId ? item.testCaseId : item.id
                }}</el-checkbox
                >
              </li>
            </ul>
          </div>

          <div class="test-case-operation">
            <p>
              <el-button
                type="primary"
                @click="clickOnAddTestCase"
                :disabled="!isTestCaseAddable"
              >添加 >
              </el-button>
            </p>
          </div>

          <div class="test-case-list selected-cases">
            <div class="case-list-title">
              已选
            </div>
            <draggable
              element="ul"
              v-model="form.testCaseList"
              :sort="true"
              :options="dragOption"
              @start="dragging = true"
              @end="dragging = false"
            >
              <transition-group
                type="transition"
                :name="!dragging ? 'flip-list' : null"
              >
                <li v-if="!form.testCaseList || form.testCaseList.length <= 0">
                  <span>请添加关联用例</span>
                </li>
                <li
                  v-for="(item, index) in form.testCaseList"
                  :key="item.id + '-' + index"
                  class="selected-case-item"
                >
                  <span class="draggable-icon"/>
                  <span
                    class="selected-case-text"
                  >{{ item.taskName }}-ID:{{
                    item.testCaseId ? item.testCaseId : item.id
                  }}</span
                  >

                  <span>
                    <i
                      class="el-icon-delete"
                      :style="{ color: '#f56c6c' }"
                      @click="clickOnDeleteTestCase(item)"
                    />
                    <!--                  <el-button type="danger" >-->
                    <!--                   -->
                    <!--                  </el-button>-->
                  </span>
                </li>
              </transition-group>
            </draggable>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button
        :loading="requesting"
        @click="visible = false">{{
          $t("cancel")
        }}</el-button>
      <el-button
        :loading="requesting"
        @click="formSubmitHandle()"
        type="primary"
      >{{ $t("confirm") }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import draggable from 'vuedraggable'
import _ from 'lodash'
import ProductTypeSelect from '../../../components/product.type.select'
export default {
  name: 'TestCollectionAddOrUpdate',
  components: { ProductTypeSelect, draggable },
  data () {
    return {
      dragging: false,
      visible: false,
      loading: false,
      requesting: false,
      producttypes: [],
      productInfos: [],
      testCases: [],
      // productTypeId: '',
      selectedInfos: [],
      dragOption: {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost',
        sort: true,
        dragoverBubble: true,
        // draggable: '.selected-case-item',
        onMove: (event, original) => {
          // console.log(event)
        }
      },
      form: {
        deviceId: '',
        collectionName: '',
        productInfoId: '',
        testCaseList: []
      }
    }
  },
  computed: {
    isTestCaseAddable () {
      let selected = this.testCases.filter(item => {
        return item.checked
      })

      return selected && selected.length > 0
    },
    isSelectedCasesDeletable () {
      let selected = this.form.testCaseList.filter(item => {
        return item.checked
      })

      return selected && selected.length > 0
    },
    dataRule () {
      return {
        collectionName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        productInfoId: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        deviceId: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        // productTypeId: [
        //   {
        //     required: true,
        //     message: this.$t('validate.required'),
        //     trigger: 'blur'
        //   }
        // ],
        testCaseList: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]

        // taskContent: [
        //   {
        //     required: true,
        //     message: this.$t('validate.required'),
        //     trigger: 'blur'
        //   }
        // ],
        // productTypeId: [
        //   {
        //     required: true,
        //     message: this.$t('validate.required'),
        //     trigger: 'blur'
        //   }
        // ],
        // sn8: [
        //   {
        //     required: true,
        //     message: this.$t('validate.required'),
        //     trigger: 'blur'
        //   }
        // ]
      }
    }
  },
  created () {},
  mounted () {
    Promise.race([
      this.loadProductType(),
      this.loadProductInfos(),
      this.loadTestCases()
    ])
  },
  methods: {
    init () {
      this.visible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()

        this.selectedInfos = []
        this.form.collectionName = ''
        this.form.productInfoId = ''
        this.form.testCaseList = []
        if (this.form.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.loading = true
      this.$http
        .get(`/product/ptestcollection/${this.form.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }

          this.form = {
            ...this.form,
            ...res.data
          }
          this.form.testCaseList = this.form.testCaseList.map(item => {
            item.checked = false
            return item
          })

          this.selectedInfos = [this.form.productInfoId]
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
        })
    },

    filterCases (query, item) {
      return item.label.indexOf(query) > -1
    },
    async loadTestCases () {
      this.$http
        .get('/product/ptestcase/page', {
          params: { page: 1, limit: 100 }
        })
        .then(res => {
          this.testCases = res.data.data.list
          /**
           *
           * .map(item => {
            // return {
            //   key: item.id,
            //   label: item.taskName,
            //   disabled: false
            // }
          })
           */
        })
    },
    async loadProductInfos () {
      this.$http
        .get('/product/pproductinfo/info', {
          params: { page: 1, limit: 100 }
        })
        .then(res => {
          this.productInfos = res.data.data.list.map(item => {
            let label = `${item.productName}`

            if (this.producttypes && this.producttypes.length > 0) {
              let finded = this.producttypes.find(type => {
                return type.id === item.productTypeId
              })
              if (finded) {
                label = `${finded.productType}-${item.productName}`
              }
            }
            return {
              label: label,
              value: item.id
            }
          })
        })
    },
    async loadProductType () {
      this.$http
        .get('/product/pproductinfo/producttypelist', {
          params: { page: 1, limit: 100 }
        })
        .then(res => {
          this.producttypes = res.data.data
        })
    },

    onProductSelectChange (value) {
      let productInfo = value && value.length > 0 ? value[0] : ''
      this.form.productInfoId = productInfo
    },
    onTypeChanged (value) {
      // this.form.productTypeId = value
    },
    onTransferChanged (value, direction, movedKeys) {
      // console.log(value, direction, movedKeys)
      // console.log(this.selectedCases)
      // this.form.testCaseIdList = this.selectedCases
      // console.log(this.form.testCaseList)
    },

    clickOnAddTestCase () {
      if (!this.isTestCaseAddable) {
        return
      }
      let selected = this.testCases.filter(item => {
        return item.checked
      })

      this.form.testCaseList = this.form.testCaseList
        .concat(_.cloneDeep(selected))
        .map(item => {
          item.checked = false
          return item
        })
      this.testCases.forEach(item => {
        item.checked = false
      })
    },

    clickOnDeleteTestCase (item) {
      // console.log(this.form.testCaseList.splice(this.form.testCaseList.indexOf(item), 1))
      this.form.testCaseList.splice(this.form.testCaseList.indexOf(item), 1)
    },

    formSubmitHandle () {
      this.$refs['dataForm'].validate(valid => {
        if (!valid) {
          return false
        }
        if (this.requesting) {
          return
        }
        let params = {
          ...this.form
          // status: this.form.status ? 1 : 0
        }

        // handle testcaseIdlist
        params.testCaseIdList = params.testCaseList.map(item => {
          return Number.parseInt(
            item.testCaseId ? item.testCaseId : item.id,
            10
          )
        })
        delete params.testCaseList
        this.requesting = true
        this.$http[!this.form.id ? 'post' : 'put'](
          '/product/ptestcollection',
          params
        )
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
          .catch(() => {})
          .finally(() => {
            this.requesting = false
          })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.code-editor-container {
  height: 30vh;
}
.product-info-item-select {
  .product-info-item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
}

.test-case-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .test-case-operation {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .test-case-list {
    flex: 2;
    /*width: 400px;*/
    height: 400px;
    max-height: 400px;
    overflow-y: auto;

    /*box-shadow: 0 0 5px 5px #eeeeee;*/
    /*border-bottom: 1px solid #eeeeee;*/
    border: 1px solid #eeeeee;
    .case-list-title {
      padding: 5px 10px;
      font-weight: bold;
      background-color: #f9f9f9;
      border: 1px solid #eeeeee;
    }
    &.original-cases {
      /*border-right: 1px solid #eeeeee;*/
    }
    &.selected-cases {
      /*border-left: 1px solid #eeeeee;*/
    }
    .flip-list-move {
      transition: transform 0.5s;
    }
    .no-move {
      transition: transform 0s;
    }
    .ghost {
      opacity: 0.5;
      background: #cccccc;
    }

    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      li {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        padding: 5px 0px;

        margin: 0 10px;
        border-bottom: 1px solid #eeeeee;

        cursor: pointer;
        transition: all 0.2s ease;
        &:hover {
          background-color: #f6f6f6;
        }

        &.selected-case-item {
          justify-content: space-between;
          .selected-case-text {
            flex: 2;
            margin-left: 20px;
            color: #606266;
            font-weight: 500;
            font-size: 14px;
            justify-content: flex-start;
          }
        }

        .draggable-icon {
          display: inline-block;
          width: 16px;
          height: 16px;
          background-repeat: no-repeat;
          background-position: center center;
          background-size: contain;
          background-image: url("");
        }
        /*.case-checkbox{*/
        /*  display: inline-block;*/
        /*  width: 25px;*/
        /*  height: 25px;*/
        /*  border-radius: 5px;*/
        /*  border: 1px solid #999999;*/
        /*  margin-right: 10px;*/
        /*}*/
      }
    }
  }
}
</style>
